package com.chenfan.mcn.event.subscriber;

import com.alibaba.fastjson.JSON;
import com.chenfan.common.vo.Response;
import com.chenfan.common.vo.ResponseCode;
import com.chenfan.mcn.clients.baseinfo.BaseInfoClient;
import com.chenfan.mcn.extension.log.FieldChangeOperateLog;
import com.chenfan.mcn.event.OperateLogBatchEvent;
import com.chenfan.mcn.extension.log.FieldChangeDTO;
import com.chenfan.mcn.extension.log.FieldChangeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wulg
 * @date 2023/10/8
 */
@Slf4j
//@Component
public class OperateLogBatchEventSubscriber implements EventSubscriber<OperateLogBatchEvent> {

    @Autowired
    private BaseInfoClient baseInfoClient;

    /**
     * 操作日志订阅实现
     *
     * @param event
     */
    @Override
    public void subscribe(OperateLogBatchEvent event) {
        List<ImmutablePair<Object, Object>> pairList = event.getValuePair();
        if(CollectionUtils.isEmpty(pairList)) {
            return;
        }
        List<FieldChangeOperateLog> logList = new ArrayList<>(16);
        pairList.forEach(pair -> {
            FieldChangeDTO<Object> fieldChangeDTO = new FieldChangeDTO<>(event.getOperationBy(), event.getOperationName(), event.getOperationTime());
            fieldChangeDTO.setBusinessId(event.getBussinessId());
            fieldChangeDTO.setBusinessType(event.getBussinessType());
            fieldChangeDTO.setOperationType(event.getOperationType());
            fieldChangeDTO.setBeforeValue(pair.getLeft());
            fieldChangeDTO.setAfterValue(pair.getRight());
            List<FieldChangeOperateLog> subLogList = FieldChangeUtil.contrast(fieldChangeDTO);
            if (CollectionUtils.isNotEmpty(subLogList)) {
                logList.addAll(subLogList);
            }
        });
        if (CollectionUtils.isEmpty(logList)) {
            return;
        }
        Response response = baseInfoClient.insertLog(logList);
        if (ResponseCode.SUCCESS.getCode() != response.getCode()) {
            log.error("操作日志生成失败！日志报文：{}", JSON.toJSONString(logList));
        }
    }
}
